<?php
class AdminGiaithuong extends CActiveRecord{

    public static function model($className = __CLASS__) {
        return parent::model ( $className );
    }   

    // goi den bang can ket noi   
    public function tableName() {                  
        return 'giai_thuong';
    }
    
    public function countRowByTypeAndName($type,$name){
        $str = "";
        if($type > 0){
            $str .= " AND type = ".$type;
        }
        if($name != ""){
            $str .= " AND name LIKE '%$name%'";    
        }
        $sql = "SELECT count(id) as count FROM giai_thuong WHERE 1".$str;
        $connect = Yii::app()->db;
        $command = $connect->createCommand($sql);
        $row = $command->queryRow();
        $result = $row['count'];
        return $result; 
    }
    
    public function getRowByTypeAndName($type,$name,$begin,$end){
        $row = array();
        $str = "";
        if($type > 0){
            $str .= " AND type = ".$type;
        }
        if($name != ""){
            $str .= " AND name LIKE '%$name%'";    
        }
        $sql = "SELECT id, name, price, image_url, type, create_date FROM giai_thuong WHERE 1".$str." LIMIT $begin,$end";
        $connect = Yii::app()->db;
        $command = $connect->createCommand($sql);
        $row = $command->queryAll();
        return $row; 
    }
    
    public function insertRow($array_input){
          $sql='';
          foreach($array_input as $key=>$value){
             $sql .= "`".$key."` = '".$value."',"; 
          }
          $sql = rtrim($sql,','); 
          $sql = 'INSERT INTO giai_thuong SET '.$sql;         
          $connect = Yii::app()->db;
          $command = $connect->createCommand($sql);
          $command->execute();
          $record_id = Yii::app()->db->getLastInsertID();  
          return $record_id;              
   }
   
    public function deleteRowById($id){
        $sql = "DELETE FROM giai_thuong WHERE id=".$id;
        $connect = Yii::app()->db;
        $command = $connect->createCommand($sql);
        $result = $command->execute(); 
        return $result;          
    }
    
    public function updateRow($name,$type,$price,$image_url,$id){
        $str = "";
        if($name != ""){
            $str .= " ,name = '$name'";    
        }
        if($price > 0){
            $str .= " ,price = '$price'";
        }
        $sql = "UPDATE giai_thuong SET type = $type, image_url = '$image_url' ".$str." WHERE id=".$id;
        $connect = Yii::app()->db;
        $command = $connect->createCommand($sql);
        $result = $command->execute();
        return $result;        
    }
    
    public function getRowById($id){
        $sql = "SELECT * FROM giai_thuong WHERE id =".$id;
        $connect = Yii::app()->db;
        $command = $connect->createCommand($sql);
        $row = $command->queryRow();       
        return $row;        
    }
}